__all__ = [
   "wanfangjournal_wanfangarticle_grpc_callback",
    "wanfangthesis_wanfangthesis_search_list_grpc_callback",
    "wanfangthesis_wanfangthesis_typelist_grpc_callback",
    "wanfangthesis_wanfangthesis_yearlist_grpc_callback",
    "wanfangthesis_wanfangthesis_search_sublist_grpc_callback",
    "wanfangthesis_wanfangthesis_search_article_grpc_callback",
    "wanfangconference_wanfangconference_search_list_grpc_callback",
    "wanfangconference_wanfangconference_typelist_grpc_callback",
    "wanfangconference_wanfangconference_yearlist_grpc_callback",
    "wanfangconference_wanfangconference_search_sublist_grpc_callback",
    "wanfangconference_wanfangconference_search_article_grpc_callback",
    "wanfangunconference_wanfangunconference_search_article_grpc_callback",
    "wanfangpatent_wanfangpatent_search_list_grpc_callback",
    "wanfangpatent_wanfangpatent_typelist_grpc_callback",
    "wanfangpatent_wanfangpatent_search_sublist_grpc_callback",
    "wanfangpatent_wanfangpatent_search_article_grpc_callback",
]

import base64
import json

from protobuf_to_dict import protobuf_to_dict


#  protoc --python_out=. .\wanfangjournal_wanfangarticle.proto 使用这个命令生成对应的py文件
def wanfangjournal_wanfangarticle_grpc_callback(pm) -> bytes:
    if pm.keys == "1_3":
        # 题录
        return wanfang_article_create_grpc(pm.post_data)
    elif pm.keys in ("1_1", "1_2"):
        # 引文 被引，结构一样 只是post_data["referencetype"]给了不同的值
        return wanfang_article_ref_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

# def wanfangjournal_wanfangarticle_grpc_result_callback(content):
#     """
#     题录结果处理
#     :param content:
#     :return:
#     """
#     from apps.crawler_platform.core_callback.grpc_callback import wanfang_article_pb2
#     search_response = wanfang_article_pb2.DetailRespService.DetailResponse()
#     content1 = content[5:-20]
#     search_response.ParseFromString(content1)
#     jdict = protobuf_to_dict(search_response)
#     strEncode = base64.b64encode(content).decode('utf8')
#     jdict["raw_base64"] = strEncode
#     str_dic = json.dumps(jdict, ensure_ascii=False)
#     return str_dic

def wanfang_search_type_create_grpc(post_data):
    from apps.crawler_platform.core_callback.grpc_callback import wanfangsearch_facet_pb2 as srpb
    search_request = srpb.SearchService.FacetSearchRequest()
    search_request.commonrequest.searchType = "paper"
    search_request.commonrequest.searchWord = post_data["searchWord"]
    ss1 = search_request.commonrequest.secondSearch.add()
    ss1.field = "Type"
    ss1.value = '{}'.format(post_data["typevalue"])
    if post_data.get("classid") != None and post_data.get("classid") != "":
        ss2 = search_request.commonrequest.secondSearch.add()
        ss2.field = "ClassCodeForSearch"
        ss2.value = '"{}"'.format(post_data["classid"])
    search_request.commonrequest.currentPage = int(post_data["p"])
    search_request.commonrequest.pageSize = int(post_data["psize"])
    search_request.commonrequest.searchFilter.append(0)
    search_request.facetField = post_data["facetField"]
    if post_data.get("fid", "") != "":
        search_request.facetPrefix = post_data["fid"]
    bytes_body = search_request.SerializeToString()
    # print(search_request)
    # 构造字节序列的头部
    blen = len(bytes_body)
    len1 = blen
    len2 = 0
    if len1 > 255:
        hlen = str(hex(blen)).replace("0x", "")
        if len(hlen) == 3:
            hlen = "0" + hlen
        len1 = int(hlen[2:4], 16)
        len2 = int(hlen[0:2], 16)
    bytes_head = bytes([0, 0, 0, len2, len1])
    # bytes_head = bytes([0, 0, 0, 0, len(bytes_body)])
    req_bytes = bytes_head + bytes_body
    return req_bytes

def wanfang_search_type_result_callback(content):
    """
    高级查询分类结果处理
    :param content:
    :return:
    """
    from apps.crawler_platform.core_callback.grpc_callback import wanfangsearch_facet_resp_pb2 as rfpb
    search_response = rfpb.FacetSearchRespService.FacetSearchResponse()
    content1 = content[5:]
    search_response.ParseFromString(content1)
    jdict = protobuf_to_dict(search_response)
    strEncode = base64.b64encode(content).decode('utf8')
    jdict["raw_base64"] = strEncode
    str_dic = json.dumps(jdict, ensure_ascii=False)
    return str_dic

def wanfang_search_list_create_grpc(post_data):
    from apps.crawler_platform.core_callback.grpc_callback import wanfangsearch_list_pb2 as srpb
    search_request = srpb.SearchService.SearchRequest()
    search_request.commonrequest.searchType = "paper"
    search_request.commonrequest.searchWord = post_data["searchWord"]
    ss1 = search_request.commonrequest.secondSearch.add()
    ss1.field = "Type"
    ss1.value = '{}'.format(post_data["typevalue"])
    ss2 = search_request.commonrequest.secondSearch.add()
    ss2.field = "ClassCodeForSearch"
    ss2.value = '"{}"'.format(post_data["class_id"])
    years = post_data["years"]
    if str(post_data["years"]) != "9999":
        ss3 = search_request.commonrequest.secondSearch.add()
        ss3.field = post_data["ss3_field"]
        ss3.value = '"{}"'.format(years)
    search_request.commonrequest.searchSort.field = post_data["sort_by"]
    search_request.commonrequest.searchSort.order = 1
    search_request.commonrequest.currentPage = int(post_data["p"])
    search_request.commonrequest.pageSize = 50
    search_request.commonrequest.searchFilter.append(0)
    bytes_body = search_request.SerializeToString()
    # print(search_request)
    # 构造字节序列的头部
    bytes_head = None
    blen = len(bytes_body)
    len1 = blen
    len2 = 0
    if len1 > 255:
        hlen = str(hex(blen)).replace("0x", "")
        if len(hlen) == 3:
            hlen = "0" + hlen
        len1 = int(hlen[2:4], 16)
        len2 = int(hlen[0:2], 16)
    bytes_head = bytes([0, 0, 0, len2, len1])
    # bytes_head = bytes([0, 0, 0, 0, len(bytes_body)])
    req_bytes = bytes_head + bytes_body
    return req_bytes

def wanfang_search_list_result_callback(content):
    """
    高级列表查询结果处理
    :param content:
    :return:
    """
    from apps.crawler_platform.core_callback.grpc_callback import wanfangsearch_list_resp_pb2 as rfpb
    search_response = rfpb.SearchRespService.SearchResponse()
    content1 = content[5:]
    search_response.ParseFromString(content1)
    jdict = protobuf_to_dict(search_response)
    strEncode = base64.b64encode(content).decode('utf8')
    jdict["raw_base64"] = strEncode
    str_dic = json.dumps(jdict, ensure_ascii=False)
    return str_dic

def wanfang_article_create_grpc(post_data):
    from apps.crawler_platform.core_callback.grpc_callback import wanfang_article_pb2
    detail_request = wanfang_article_pb2.DetailInfoRequest.requestInfo()
    detail_request.resourcetype = post_data["resourcetype"]
    detail_request.id = post_data["id"]
    detail_request.referer = ""
    detail_request.md5id = ""
    detail_request.transaction = ""
    bytes_body = detail_request.SerializeToString()
    # 构造字节序列的头部
    blen = len(bytes_body)
    len1 = blen
    len2 = 0
    if len1 > 255:
        hlen = str(hex(blen)).replace("0x", "")
        if len(hlen) == 3:
            hlen = "0" + hlen
        len1 = int(hlen[2:4], 16)
        len2 = int(hlen[0:2], 16)
    bytes_head = bytes([0, 0, 0, len2, len1])
    # bytes_head = bytes([0, 0, 0, 0, len(bytes_body)])
    req_bytes = bytes_head + bytes_body
    return req_bytes

def wanfang_article_ref_create_grpc(post_data):
    from apps.crawler_platform.core_callback.grpc_callback import wanfang_article_pb2
    detail_request = wanfang_article_pb2.DetailInfoRequest.refRequestInfo()
    detail_request.referencetype = post_data["referencetype"]
    detail_request.id = post_data["id"]
    detail_request.pagenum = int(post_data["pagenum"])
    bytes_body = detail_request.SerializeToString()
    # 构造字节序列的头部
    blen = len(bytes_body)
    len1 = blen
    len2 = 0
    if len1 > 255:
        hlen = str(hex(blen)).replace("0x", "")
        if len(hlen) == 3:
            hlen = "0" + hlen
        len1 = int(hlen[2:4], 16)
        len2 = int(hlen[0:2], 16)
    bytes_head = bytes([0, 0, 0, len2, len1])
    # bytes_head = bytes([0, 0, 0, 0, len(bytes_body)])
    req_bytes = bytes_head + bytes_body
    return req_bytes

def wanfang_article_grpc_result_callback(content):
    """
    题录结果处理
    :param content:
    :return:
    """
    from apps.crawler_platform.core_callback.grpc_callback import wanfang_article_pb2
    search_response = wanfang_article_pb2.DetailRespService.DetailResponse()
    # content1 = content[5:-20]
    content1 = content[5:]
    search_response.ParseFromString(content1)
    jdict = protobuf_to_dict(search_response)
    # print(content1)
    strEncode = base64.b64encode(content).decode('utf8')
    jdict["raw_base64"] = strEncode
    str_dic = json.dumps(jdict, ensure_ascii=False)
    return str_dic

def wanfangthesis_wanfangthesis_search_list_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_type_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangthesis_wanfangthesis_typelist_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        # post_data = pm.post_data
        # post_data.update({
        #     "searchWord": '学位授予单位:({})'.format(post_data["search_name"]),
        #     "typevalue": '"Thesis"'
        # })
        return wanfang_search_type_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangthesis_wanfangthesis_yearlist_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_type_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangthesis_wanfangthesis_search_sublist_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_list_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangthesis_wanfangthesis_search_article_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_article_create_grpc(pm.post_data)
    elif pm.keys in ("1_2", "1_3"):
        # 引文 被引，结构一样 只是post_data["referencetype"]给了不同的值
        return wanfang_article_ref_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangconference_wanfangconference_search_list_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_type_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangconference_wanfangconference_typelist_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_type_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangconference_wanfangconference_yearlist_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_type_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangconference_wanfangconference_search_sublist_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_list_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangconference_wanfangconference_search_article_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_article_create_grpc(pm.post_data)
    elif pm.keys in ("1_2", "1_3"):
        # 引文 被引，结构一样 只是post_data["referencetype"]给了不同的值
        return wanfang_article_ref_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangunconference_wanfangunconference_search_article_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_article_create_grpc(pm.post_data)
    elif pm.keys in ("1_2", "1_3"):
        # 引文 被引，结构一样 只是post_data["referencetype"]给了不同的值
        return wanfang_article_ref_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangpatent_wanfangpatent_search_list_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_type_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangpatent_wanfangpatent_typelist_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_type_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangpatent_wanfangpatent_yearlist_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_type_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangpatent_wanfangpatent_search_sublist_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_search_list_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")

def wanfangpatent_wanfangpatent_search_article_grpc_callback(pm) -> bytes:
    if pm.keys == "1_1":
        return wanfang_article_create_grpc(pm.post_data)
    else:
        raise Exception("没有相关配置")
